/*
 * Copyright 2018-2021 guerlab.net and other contributors.
 *
 * Licensed under the GNU LESSER GENERAL PUBLIC LICENSE, Version 3 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package net.guerlab.smart.pay.api.autoconfig;

import lombok.AllArgsConstructor;
import net.guerlab.smart.pay.api.PayLogNotifyApi;
import net.guerlab.smart.pay.core.domain.PayLogNotifyDTO;
import net.guerlab.smart.pay.core.exception.PayLogNotifyInvalidException;
import net.guerlab.smart.pay.core.searchparams.PayLogNotifySearchParams;
import net.guerlab.smart.pay.service.service.PayLogNotifyService;
import net.guerlab.smart.platform.commons.util.BeanConvertUtils;
import net.guerlab.web.result.ListObject;
import org.springframework.context.annotation.*;
import org.springframework.core.type.AnnotatedTypeMetadata;
import org.springframework.lang.NonNull;

import java.util.List;

/**
 * 支付记录通知服务接口本地实现
 *
 * @author guer
 */
@Configuration
@Conditional(PayLogNotifyApiLocalServiceAutoConfigure.WrapperCondition.class)
public class PayLogNotifyApiLocalServiceAutoConfigure {

    @SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
    @Bean
    public PayLogNotifyApi payLogNotifyApiLocalServiceWrapper(PayLogNotifyService service) {
        return new PayLogNotifyApiLocalServiceWrapper(service);
    }

    public static class WrapperCondition implements Condition {

        @Override
        public boolean matches(@NonNull ConditionContext context, @NonNull AnnotatedTypeMetadata metadata) {
            try {
                return WrapperCondition.class.getClassLoader().loadClass("net.guerlab.smart.pay.service.service.PayLogNotifyService") != null;
            } catch (Exception e) {
                return false;
            }
        }
    }

    @AllArgsConstructor
    private static class PayLogNotifyApiLocalServiceWrapper implements PayLogNotifyApi {

        private final PayLogNotifyService service;

        @Override
        public PayLogNotifyDTO findOne(Long payLogNotifyId) {
            return service.selectByIdOptional(payLogNotifyId).orElseThrow(PayLogNotifyInvalidException::new).convert();
        }

        @Override
        public ListObject<PayLogNotifyDTO> findList(PayLogNotifySearchParams searchParams) {
            return BeanConvertUtils.toListObject(service.selectPage(searchParams));
        }

        @Override
        public List<PayLogNotifyDTO> findAll(PayLogNotifySearchParams searchParams) {
            return BeanConvertUtils.toList(service.selectAll(searchParams));
        }
    }

}
